import React, { useEffect, useState } from 'react';
import '@/views/Index/Users/Users.scss'
import Nav from '../../../components/Nav/Nav'
import service from '../../../api/index'
import type { ColumnsType } from 'antd/es/table';

import { message, Table, Button, Tag, Drawer,Form,Input,Select,Tree } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useNavigate } from "react-router-dom";
import type { DataNode } from 'antd/es/tree';


interface Props {

}
interface DataType {
    order: number;
    adminname: string;
    role: number;
    adminid: string;
}

function Users(props: Props) {

    let [form] = Form.useForm()

    let navigate = useNavigate()
    // 产品总数量
    let [total, setTotal] = useState()

    var [checkedKeys,setCheckedKeys] = useState<string[]>([]);

    let [open, setOpen] = useState<boolean>(false)
    // 表格数据源
    let [dataSource, setDateSource] = useState<DataType[]>([])

    // 表格头部
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            // dataIndex: 'order',
            key: 'order',
            align: 'center',
            render: (_, record) => <a>{dataSource.indexOf(record) + 1}</a>,
        },
        {
            title: '账号',
            dataIndex: 'adminname',
            key: 'adminname',
            align: 'center',
        },
        {
            title: '权限',
            dataIndex: 'role',
            key: 'role',
            align: 'center',
            render: (_, record) => {
                return <>
                    {
                        record.role == 1 ?
                            <Tag color="#87d068">超级管理员</Tag>
                            :
                            <Tag color="#108ee9">管理员</Tag>
                    }
                </>
            }
        },
        {
            title: '操作',
            align: 'center',
            // dataIndex: 'make',
            // key: 'adminname',
            render: (_, record) => {
                return <>
                    <Button className='edit' onClick={()=>{adminEdit(record)}}>
                        Edit
                    </Button>
                    <Button className='remove' type="primary" danger onClick={() => {
                        adminDelete(record.adminid)
                    }}>
                        Delete
                    </Button>
                </>

            }


        },
    ];

    // 发送轮播图列表请求
    let adminlist = async (payload = {}) => {
        let res = await service.admin.admin_list(payload)
        // console.log(res.data);
        if (res.data.code == '200') {
            // 给数据添加key属性
            res.data.data.map((item: any) => {
                item.key = item.adminid
            })
            setDateSource(res.data.data)
            setTotal(res.data.data.length)
        }
    }

    // 发请求
    useEffect(() => {
        adminlist()
    }, [])

    let code = (res: any) => {
        if (res.data.code == '200') {
            message.success({
                content: res.data.message,
                style: {
                    marginTop: '20vh',
                },
            })
            adminlist()
        } else {
            message.error({
                content: res.data.message,
                style: {
                    marginTop: '20vh',
                },
            })
        }
    }

    // 添加管理员信息
    let adminAdd = () => {
        setOpen(true)
    }

    // 点X执行
    let onClose = () => {
        //清空表单
        form.setFieldsValue({adminid:'',adminname:'',password:'',role:'',checkedKeys:[]});
        setCheckedKeys([]);
        setOpen(false)
    }

    // 修改管理员信息
    let adminEdit = async (record:any) => {
        //1.显示抽屉
        setOpen(true);

        //2.回显表单内容
        form.setFieldsValue( record );

        setCheckedKeys(record.checkedKeys);
    }
    // 删除管理员信息
    let adminDelete = async (adminid: any) => {
        console.log(adminid);
        let res = await service.admin.admin_delete({ adminid })
        // console.log(res);
        code(res)
    }
    // 分页设置
    let pageChange = (page: any, pageSize: any) => {
        // console.log(page, pageSize);
        adminlist({ count: page, limitNum: pageSize })
    };

    //权限数据
    const treeData: DataNode[] = [
        {
          title: '轮播图管理',
          key: '0-0',
          children: [
            {
              title: '轮播图列表',
              key: '0-0-0'
            }
          ],
        },
        {
          title: '账号管理',
          key: '0-1',
          children: [
            { title: '管理员列表', key: '0-1-0' },
          ],
        },
        {
          title: '产品管理',
          key: '0-2',
          children: [
            { title: '产品列表', key: '0-2-0' },
            { title: '秒杀列表', key: '0-2-1' },
            { title: '推荐列表', key: '0-2-2' },
            { title: '筛选列表', key: '0-2-3' },
          ],
        },
        {
          title: '数据可视化',
          key: '0-3',
          children: [
            { title: 'echarts使用', key: '0-3-0' },
          ],
        },
        {
          title: '编辑器',
          key: '0-4',
          children: [
            { title: '富文本编辑器', key: '0-4-0' },
          ],
        },
        {
          title: 'Excel管理',
          key: '0-5',
          children: [
            { title: 'excel导入', key: '0-5-0' },
            { title: 'excel导出', key: '0-5-1' },
          ],
        },
        {
          title: '地图管理',
          key: '0-6',
          children: [
            { title: '百度地图', key: '0-6-0' },
          ],
        },
    ];

    //表单验证通过时执行
    var onFinish =  async (formvalues:any)=>{
        console.log(formvalues);
        
        if( formvalues.adminid ){ //如果有adminid,执行编辑
            var res = await service.admin.admin_update( formvalues )
            if( res.data.code == 200 ){
                //清空表单
                form.setFieldsValue({ adminid:'', adminname:'',password:'',role:'',checkedKeys:[]});
                //关闭抽屉
                setOpen(false);
                code(res)
            }else{
                message.error({ content:'更新管理员失败!' });
            }
        }else{ //没有adminid, 执行新增
            var res = await service.admin.admin_add( formvalues )
            if( res.data.code == 200 ){
                //清空表单
                form.setFieldsValue({adminname:'',password:'',role:'',checkedKeys:[]});
                //关闭抽屉
                setOpen(false);
                code(res)
            }else{
                message.error({ content:'添加管理员失败!' });
            }
        }
    }
    //树形控件(权限)的复选框 勾选发生变化时执行
    var onCheck = (checkedKeys:any)=>{
        // console.log(checkedKeys);
        
        form.setFieldValue('checkedKeys',checkedKeys);//设置表单项checkedKeys的值
        setCheckedKeys( checkedKeys ) //保存选中的key值到受控属性中.
        // form.setFieldsValue();//所有表单项的回显 使用这个方法
    }


    return (
        <div className='users'>
            <Nav />
            <div className="list">
                <div className="btn">
                    <Button className='add' type="primary" onClick={adminAdd}>
                        添加管理员<PlusOutlined />
                    </Button>
                </div>
                <Table className='table' dataSource={dataSource} columns={columns} scroll={{ y: 380 }} pagination={{
                    showSizeChanger: false,
                    onChange: pageChange,
                    defaultCurrent: 1,
                    total: total
                }} />
                <Drawer title="添加/编辑管理员" placement="right" onClose={onClose} open={open}>
                    <Form
                        form={form}
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 14 }}
                        layout="horizontal"
                        style={{ maxWidth: 600 }}
                        onFinish={onFinish}
                    >
                        <Form.Item
                            label="adminid"
                            name="adminid"
                            hidden  //设置该表单项为隐藏表单项,页面上看不到该项,在提交表单时依然会收集该项的值.
                        >
                            <Input disabled={form.getFieldValue('adminid')} />
                        </Form.Item>
                        <Form.Item
                            label="账号"
                            name="adminname"
                            rules={[{ required: true, message: '请输入账号' }]}>
                            <Input disabled={form.getFieldValue('adminid')} placeholder='请输入账号' />
                        </Form.Item>
                        <Form.Item
                            label="密码"
                            name="password"
                            rules={[{ required: true, message: '请输入密码' }]}>
                            <Input disabled={form.getFieldValue('adminid')} placeholder='请输入密码' />
                        </Form.Item>
                        <Form.Item
                            label="角色"
                            name="role"
                            rules={[{ required: true, message: '请选择角色' }]}
                        >
                            <Select
                                style={{ width: 120 }}
                                options={[
                                    { value: 2, label: '管理员' },
                                    { value: 1, label: '超级管理员' }
                                ]}
                            />
                        </Form.Item>
                        <Form.Item
                            label="权限"
                            name="checkedKeys"
                            rules={[{ required: true, message: '请选择权限' }]}>
                            <Tree
                                checkable
                                treeData={treeData}
                                onCheck={onCheck} //
                                checkedKeys={checkedKeys} //受控属性
                            // defaultCheckedKeys  //非受控属性,默认选中( 只在组件初次渲染时渲染一次 )
                            />
                        </Form.Item>

                        <Form.Item  >
                            <Button type='primary' htmlType="submit"> {form.getFieldValue('adminid') ? '更新管理员' : '添加管理员'} </Button>
                        </Form.Item>
                    </Form>
                </Drawer>
            </div>
        </div>
    );
}

export default Users;